package com.gxa.day2022_07_20;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginFrame {
    //准备一个数组用来存储所有账户信息
    private static Account[] accounts = new Account[30];


    public static void main(String[] args) {
        LoginFrame loginFrame = new LoginFrame();

        loginFrame.lauchFrame();
    }

    private void lauchFrame() {
        JFrame loginFrame = new JFrame("登录界面");
        loginFrame.setSize(600, 400);
        loginFrame.setLocationRelativeTo(null);//居中
        loginFrame.setLayout(null);//不需要布局管理器
        loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        addWidget2Frame(loginFrame);//添加组件到loginFrame

        loginFrame.setVisible(true);
    }

    private void addWidget2Frame(JFrame loginFrame) {
        JLabel idLabel = new JLabel("卡号：");
        idLabel.setBounds(200, 150, 50, 20);
        JTextField idField = new JTextField();
        idField.setBounds(260, 150, 150, 20);

        JLabel pwdLabel = new JLabel("密码：");
        pwdLabel.setBounds(200, 200, 50, 20);
        JPasswordField pwdField = new JPasswordField();
        pwdField.setBounds(260, 200, 150, 20);

        JButton loginButton = new JButton("登录");
        loginButton.setBounds(300, 240, 80, 20);
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //1.获取输入的卡号
                String id = idField.getText();
                //2.获取输入的密码
//                String pwd = pwdField.getText(  );
                String pwd = pwdField.getPassword().toString();

                //验证卡号和密码--登录，如果卡号密码正确 进入下一界面
                //卡号密码不正确 提示用户卡号或密码错误
                Account account = new Account(id,pwd);
                if(account != null) {
                    //跳转
                    MainFrame mainFrame  =new MainFrame();
                    mainFrame.lauchFrame(account);
                    loginFrame.dispose();
                }else {
//                    System.out.println("用户名或密码错误！");
                    JOptionPane.showMessageDialog(null,"卡号或密错误");
                }
            }
        });

        loginFrame.add(idLabel);
        loginFrame.add(idField);
        loginFrame.add(pwdLabel);
        loginFrame.add(pwdField);
        loginFrame.add(loginButton);
    }

    public Account login(String id,String pwd){
        for(Account account : accounts){
            if(id.equals(account.getId()) && pwd.equals(account.getPwd())){
                return account;
            }
        }
        return null;
    }

    /**
     * 初始化账户的方法
     */
    static private void initAccount() {
        Account account = null;
        for(int i=0;i<30;i++){
             account  = new Account("54321" +i,"123",0000);
            accounts[i] = account;
        }
    }

    /**
     * static 代码块 比main先执行，
     */
    static {
        initAccount();
    }
}

